package cn.cj.erp.common.utils.encrypt;

import cn.cj.erp.common.exception.ServiceException;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * des加解密工具
 *
 * @author chenjian
 */
@Slf4j
public class DesUtil {
    private static final String DES_MODE = "DESede";

    public static final String DEFAULT_KEY = "ASDE23451234689YUIT12345";

    /**
     * 生成des计算的key
     *
     * @param key 传入的key
     * @return SecretKey对象
     */
    private static SecretKey handleKey(String key) {
        if (StrUtil.isEmpty(key)) {
            return new SecretKeySpec(DEFAULT_KEY.getBytes(), DES_MODE);
        }
        byte[] bytes = key.getBytes(StandardCharsets.UTF_8);
        // key的长度是8的倍数
        int realKeyLength = bytes.length % 8 == 0 ? bytes.length : (bytes.length / 8 + 1) * 8;
        byte[] realKey = new byte[realKeyLength];
        System.arraycopy(bytes, 0, realKey, 0, bytes.length);
        return new SecretKeySpec(realKey, DES_MODE);
    }

    /**
     * 加密
     *
     * @param inStr     需要加密的内容
     * @param secretKey 密钥
     * @return 加密后的数据
     */
    public static String encrypt(String inStr, String secretKey) {
        SecretKey desKey = handleKey(secretKey);
        Cipher cipher;
        try {
            cipher = Cipher.getInstance(DES_MODE);
            cipher.init(Cipher.ENCRYPT_MODE, desKey);
            byte[] encryptBytes = cipher.doFinal(inStr.getBytes(StandardCharsets.UTF_8));
            return Base64Util.encode(encryptBytes);
        } catch (Exception e) {
            log.error("\nDES encrypt error. ", e);
            throw new ServiceException("DES encrypt error", e);
        }
    }

    /**
     * 解密
     *
     * @param inStr     需要解密的内容
     * @param secretKey 密钥
     * @return 解密后的数据
     */
    public static String decrypt(String inStr, String secretKey) {
        SecretKey desKey = handleKey(secretKey);
        Cipher cipher;
        String outStr = null;
        try {
            cipher = Cipher.getInstance(DES_MODE);
            cipher.init(Cipher.DECRYPT_MODE, desKey);
            outStr = new String(cipher.doFinal(Base64Util.decode(inStr)), StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("DES encrypt error. ", e);
        }
        return outStr;
    }
}
